package com.xgst.lib.http;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.hjq.http.EasyLog;
import com.hjq.http.config.IRequestHandler;
import com.hjq.http.exception.DataException;
import com.hjq.http.exception.HttpException;
import com.hjq.http.exception.NetworkException;
import com.hjq.http.exception.NullBodyException;
import com.hjq.http.exception.ResponseException;
import com.hjq.http.exception.ServerException;
import com.hjq.http.request.HttpRequest;
import com.xgst.baselib.BaseApplication;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.UnknownHostException;

import okhttp3.Headers;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class RequestHandler implements IRequestHandler {

    @NonNull
    @Override
    public Object requestSuccess(@NonNull HttpRequest<?> httpRequest, @NonNull Response response, @NonNull Type type) throws Exception {
        if (Response.class.equals(type)) {
            return response;
        }

        if (!response.isSuccessful()) {
            String api = httpRequest.getRequestApi().getApi();
            throw new ResponseException("请求错误: "+api+"  "+response.code()+" : "+response.message(), response);
        }

        if (Headers.class.equals(type)) {
            return response.headers();
        }

        ResponseBody body = response.body();
        if (body == null) {
            throw new NullBodyException("ResponseBody为空");
        }

        if (ResponseBody.class.equals(type)) {
            return body;
        }

        // 如果是用数组接收，判断一下是不是用 byte[] 类型进行接收的
        if(type instanceof GenericArrayType) {
            Type genericComponentType = ((GenericArrayType) type).getGenericComponentType();
            if (byte.class.equals(genericComponentType)) {
                return body.bytes();
            }
        }

        if (InputStream.class.equals(type)) {
            return body.byteStream();
        }

        if (Bitmap.class.equals(type)) {
            return BitmapFactory.decodeStream(body.byteStream());
        }

        String text;
        try {
            text = body.string();
        } catch (IOException e) {
            // 返回结果读取异常
            throw new DataException("body.string()异常", e);
        }

        // 打印这个 Json 或者文本
        EasyLog.printJson(httpRequest, text);

        if (String.class.equals(type)) {
            return text;
        }

        final Object result;

        try {
            result = GsonUtils.fromJson(text, type);
        } catch (Exception e) {
            // 返回结果读取异常
            throw new DataException("数据解析异常: "+httpRequest.getRequestApi(),e);
        }

        int code = JsonUtils.getInt(text, "code");
        if (code == 0 || code == 200) {
            return result;
        }
        throw  new RequestException(code+" ");
    }

    @NonNull
    @Override
    public Throwable requestFail(@NonNull HttpRequest<?> httpRequest, @NonNull Throwable e) {
        if (e instanceof HttpException) {
            LogUtils.i("requestFail ",e.getMessage());
            return e;
        }

        if (e instanceof UnknownHostException) {
            // 没有连接就是网络异常
            return new NetworkException("网络无法连接", e);
        }

        if(e instanceof ConnectException){
            return new ConnectException("无法连接服务器 "+e.getMessage());
        }

        if (e instanceof IOException) {
            return new Exception("请求失败", e);
        }

        return new HttpException(e.getMessage(), e);
    }


}
